﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using TrailMapManager.Communication;

namespace TrailMapManager.Common.Track
{
    public class TrailTrackManager : BaseViewLogic
    {
        #region Properties
        private static TrailTrackManager _instance;
        public static TrailTrackManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new TrailTrackManager();
                }
                return _instance;
            }
        }

        private ObservableCollection<TrailTrack> _tracks;
        public ObservableCollection<TrailTrack> Tracks
        {
            get
            {
                if (_tracks == null)
                {
                    _tracks = new ObservableCollection<TrailTrack>();
                    _tracks.CollectionChanged +=
                        (sender, args) =>
                        {
                            NotifyPropertyChanged("TracksCount");
                        };
                }
                return _tracks;
            }
        }

        public int TracksCount
        {
            get
            {
                if (Tracks != null)
                {
                    return Tracks.Count;
                }
                return 0;
            }
        }



        #endregion

        bool trackinProgress;
        internal void AddTrackList(Communication.TrailTrackTransfer track)
        {
            IsBusy = true;
            if (!trackinProgress)
            {
                Tracks.Clear();

            }
            trackinProgress = true;
            var notCompletedTrack = (from t in Tracks
                                     where t.Id == track.Id
                                     select t).FirstOrDefault();
            if (notCompletedTrack != null)
            {
                notCompletedTrack.ParsePointData(track.PointDatas);
            }
            else
            {
                var trailTrack = new TrailTrack()
                {
                    Name = track.Name,
                    Description = track.Description,
                    Distance = track.Distance,
                    Duration = track.Duration,
                    Id = track.Id,
                };
                trailTrack.ParsePointData(track.PointDatas);
                Tracks.Add(trailTrack);
            }
        }

        public void DeleteTrack(Guid guid)
        {
            CommunicationManager.Instance.AddNewCommandToQueue(new TrailTrackDeleteCommand()
            {
                Id = guid,
                Type = CommandType.DeleteTrack,
            });
        }

        internal void UploadFinished()
        {
            trackinProgress = false;
            IsBusy = false;
        }

        internal void ClearAll()
        {
            Tracks.Clear();
        }

        public void GenerateGPX(Guid guid, string path)
        {
            var convertTrack = (from track in Tracks
                                where track.Id == guid
                                select track).FirstOrDefault();
            var gpx = new gpxType();
            gpx.creator = "Trailmap Manager";
            gpx.trk = new trkType[1];
            gpx.trk[0] = new trkType();
            gpx.trk[0].name = convertTrack.Name;
            gpx.trk[0].trkseg = new trksegType[1];
            gpx.trk[0].trkseg[0] = new trksegType();
            gpx.trk[0].trkseg[0].trkpt = new wptType[convertTrack.Points.Count];
            for (int i = 0; i < convertTrack.Points.Count; i++)
            {
                gpx.trk[0].trkseg[0].trkpt[i] = new wptType()
                {
                    lat = (decimal)convertTrack.Points[i].Position.Latitude,
                    lon = (decimal)convertTrack.Points[i].Position.Longitude,
                    ele = (decimal)convertTrack.Points[i].Altitude,
                    eleSpecified = true,
                    time = convertTrack.Points[i].TimeStamp,
                    timeSpecified = true,
                };
            }

            //DataContractSerializer dcs = new DataContractSerializer(typeof(gpxType));
            //FileStream fs = new FileStream("tempTrack.gpx", FileMode.CreateNew);
            //dcs.WriteObject(fs, gpx);
            string retVal = string.Empty;

            TextWriter writer = new StreamWriter(path, false);
            XmlSerializer serializer = new XmlSerializer(gpx.GetType());

            serializer.Serialize(writer, gpx);
            writer.Close();
            //retVal = writer.ToString();
            //return retVal;


            //return gpx.ToString();

        }
    }
}
